package com.aigou.admin.aigouspringboot.asspect;

import com.aigou.admin.aigouspringboot.common.LogScope;
import com.aigou.admin.aigouspringboot.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * @Author Mr.LiFuXing
 * @Date 2024/11/10 12:08
 * @Title LogAspect
 * @Package com.lifuixng.crmservicecode.aspect
 */

@Aspect
@Component
@Slf4j
public class LogAspect {

    ThreadLocal<Long> startTime = new ThreadLocal<>();


    @Pointcut(value = "@annotation(com.aigou.admin.aigouspringboot.common.LogScope)")
    public void operaLogPointCut() {
    }

    @Before("operaLogPointCut()")
    public void beforeMethod() {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(value = "operaLogPointCut()")
    public void saveOperaLog(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            // 拿到方法上的注解
            LogScope myLog = methodSignature.getMethod().getDeclaredAnnotation(LogScope.class);
            // 模块名称
            log.info("模块名称：{}",myLog.title());
            // 模块内容
            log.info("方法执行内容：{}",myLog.content());
            // 将入参转换成json
            String params = JSONUtils.toJSON(joinPoint.getArgs());
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = methodSignature.getMethod().getName();
            methodName = className + "." + methodName + "()";
            log.info("请求URI：{}",request.getRequestURI());
            log.info("请求方法为：{}",methodName);
            log.info("请求方式为：{}",request.getMethod());
            log.info("请求参数为：{}",params);
            log.info("请求时间为：{}",new Date());
            Long takeTime = System.currentTimeMillis() - startTime.get();// 记录方法执行耗时时间（单位：毫秒）
            log.info("耗时：{}",takeTime);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
